import { Test } from '@nestjs/testing';
import { INestApplication } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import { TypeOrmModule } from '@nestjs/typeorm';
import { RedisModule } from 'nestjs-redis';
import { getConnection } from 'typeorm';
import { Redis } from 'ioredis';

// 全局测试设置
beforeAll(async () => {
  // 设置测试环境变量
  process.env.NODE_ENV = 'test';
  process.env.DATABASE_HOST = 'localhost';
  process.env.DATABASE_PORT = '5432';
  process.env.DATABASE_USERNAME = 'test';
  process.env.DATABASE_PASSWORD = 'test';
  process.env.DATABASE_NAME = 'facetime_test';
  process.env.REDIS_HOST = 'localhost';
  process.env.REDIS_PORT = '6379';
  process.env.REDIS_DB = '1'; // 使用不同的数据库
});

// 每个测试后清理
afterEach(async () => {
  // 清理数据库连接
  try {
    const connection = getConnection();
    if (connection.isConnected) {
      await connection.synchronize(true); // 重置数据库
    }
  } catch (error) {
    // 连接可能不存在，忽略错误
  }
});

// 全局测试清理
afterAll(async () => {
  // 关闭数据库连接
  try {
    const connection = getConnection();
    if (connection.isConnected) {
      await connection.close();
    }
  } catch (error) {
    // 连接可能不存在，忽略错误
  }

  // 清理 Redis 连接
  // 这里需要根据实际的 Redis 客户端实现来清理
});

// 测试工具函数
export const createTestApp = async (
  moduleMetadata: any,
): Promise<INestApplication> => {
  const moduleRef = await Test.createTestingModule({
    imports: [
      ConfigModule.forRoot({
        isGlobal: true,
        envFilePath: '.env.test',
      }),
      TypeOrmModule.forRoot({
        type: 'sqlite',
        database: ':memory:',
        entities: [__dirname + '/../src/**/*.entity{.ts,.js}'],
        synchronize: true,
        logging: false,
      }),
      ...(moduleMetadata.imports || []),
    ],
    controllers: moduleMetadata.controllers || [],
    providers: moduleMetadata.providers || [],
  }).compile();

  const app = moduleRef.createNestApplication();
  await app.init();
  return app;
};

// Mock 数据生成器
export const mockRoom = {
  id: '123e4567-e89b-12d3-a456-426614174000',
  name: 'Test Room',
  description: 'Test room description',
  password: null,
  maxParticipants: 10,
  isActive: true,
  createdAt: new Date(),
  updatedAt: new Date(),
};

export const mockParticipant = {
  id: '123e4567-e89b-12d3-a456-426614174001',
  socketId: 'socket123',
  nickname: 'Test User',
  isAudioEnabled: true,
  isVideoEnabled: true,
  isScreenSharing: false,
  joinedAt: new Date(),
};

// 测试超时设置
jest.setTimeout(30000);

// 抑制控制台输出（可选）
if (process.env.NODE_ENV === 'test') {
  console.log = jest.fn();
  console.error = jest.fn();
  console.warn = jest.fn();
}
